﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using DevComponents.DotNetBar;
using System.IO;
using System.Xml;

namespace AMS.UI.Menu
{
    /// <summary>
    /// 用DotNetBar实现的菜单的菜单生成器
    /// </summary>
    public class BarMainMenu : BaseMenuGenerator
    {
        private IMenuClickAction barNotifier;
        /// <summary>
        /// 菜单点击通知事件，使用默认的 BarFormShowAction 类作为通知接收器
        /// </summary>
        public override IMenuClickAction MenuClickAction
        {
            get
            {
                if (barNotifier == null)
                {
                    barNotifier = BarFormShowAction.Instance;
                }

                return barNotifier;
            }
            set { barNotifier = value; }
        }

        /// <summary>
        /// 创建菜单
        /// </summary>
        /// <param name="removeExistingItems"></param>
        /// <param name="authorizedItems"></param>
        public override void CreateMenu(bool removeExistingItems, string[] authorizedItems)
        {
            base.CreateMenu(removeExistingItems, authorizedItems);
            Bar bar = (Bar)MenuControl;
            if (removeExistingItems)
            {
                bar.Items.Clear();
            }

            List<MenuItemInfo> menus = CreateAuthorizedMenuInfoList();
            foreach (MenuItemInfo menuInfo in menus)
            {
                ButtonItem bi = CreateMenuItem(menuInfo);
                bar.Items.Add(bi);
                CreateSubMenuItems(bi, menuInfo);
            }
        }

        /// <summary>
        /// 递归地创建菜单
        /// </summary>
        /// <param name="parentMenuItem"></param>
        /// <param name="menuInfo"></param>
        private void CreateSubMenuItems(ButtonItem parentMenuItem, MenuItemInfo menuInfo)
        {
            foreach (MenuItemInfo subMenuInfo in menuInfo.SubItems)
            {
                ButtonItem bi = CreateMenuItem(subMenuInfo);
                parentMenuItem.SubItems.Add(bi);
                CreateSubMenuItems(bi, subMenuInfo);
            }
        }

        /// <summary>
        /// 创建一个buttonItem
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        private ButtonItem CreateMenuItem(MenuItemInfo item)
        {
            ButtonItem bi = new ButtonItem();
            bi.Name = "mi" + item.Name;
            bi.Tag = item.Name;
            bi.Text = item.Caption;
            if (!item.HasSubItems())
            {
                bi.Click += new EventHandler(menuItem_Click);
            }

            return bi;
        }

    }
}
